package com.dw.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dw.core.entity.Admin;
import com.dw.core.entity.AdminRole;
import com.dw.core.entity.Role;
import com.dw.core.mapper.IRoleMapper;
import com.dw.core.service.IAdminRoleService;
import com.dw.core.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author zhangjing
 * @date 2020/8/21 14:55
 * @Description
 */
@Service
public class RoleServiceImpl extends ServiceImpl<IRoleMapper, Role> implements IRoleService {

    @Autowired
    IAdminRoleService adminRoleService;

    /**
     * find roles by admin
     *
     * @param admin
     * @return
     */
    @Override
    public List<Role> findRolesByAdmin(Admin admin) {

        List<AdminRole> adminRoles = adminRoleService.list(new LambdaQueryWrapper<AdminRole>().eq(AdminRole::getAdminId, admin.getId()));
        if (CollectionUtils.isEmpty(adminRoles)) {
            return new ArrayList<>();
        }
        List<Long> roleIds = new ArrayList<>();
        adminRoles.forEach(adminRole -> roleIds.add(adminRole.getId()));
        return this.list(new LambdaQueryWrapper<Role>().in(Role::getId, roleIds));
    }

    /**
     * get role keys
     *
     * @param admin
     * @return
     */
    @Override
    public Set<String> getRoleKeysByAdmin(Admin admin) {
        List<Role> roles = this.findRolesByAdmin(admin);
        return roles.stream().map(Role::getRoleKey).collect(Collectors.toSet());
    }
}
